package com.youtills.core.mybatis;

import com.youtills.core.db.DataSourceType;
import com.youtills.core.db.YoutillsDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
//import org.apache.ibatis.io.Resources;
//import org.apache.ibatis.mapping.Environment;
//import org.apache.ibatis.session.Configuration;
//import org.apache.ibatis.session.SqlSessionFactory;
//import org.apache.ibatis.session.SqlSessionFactoryBuilder;
//import org.apache.ibatis.transaction.TransactionFactory;
//import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by IntelliJ IDEA.
 * User: ravi
 * Date: 8/25/12
 * Time: 11:11 AM
 * To change this template use File | Settings | File Templates.
 */
public class MybatisSqlSessionFactoryBuilder {

//    public SqlSessionFactory get(String dataSourceType){

//        DepoDataSource dataSource = DepoDataSource.getDataSource(dataSourceType);
//        TransactionFactory transactionFactory = new JdbcTransactionFactory();
//        Environment environment = new Environment("development", transactionFactory, dataSource);
//        Configuration configuration = new Configuration(environment);
//        configuration.addLoadedResource("");
//configuration.addMapper(BlogMapper.class);
//        return new SqlSessionFactoryBuilder().build(configuration);
//    }


    public static SqlSessionFactory buildSessionFactory(String mybatisConfigXmlFile, DataSourceType dataSourceType){

        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(mybatisConfigXmlFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String env = "quiggle";
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream, env);

        YoutillsDataSource dataSource = YoutillsDataSource.getDataSource(dataSourceType);
        TransactionFactory transactionFactory = new JdbcTransactionFactory();

        Environment environment = new Environment(env, transactionFactory, dataSource);

        Configuration configuration = factory.getConfiguration();
        configuration.setEnvironment(environment);

        return factory;
    }
}
